package controller

import (
	"net/http"
	"pan/config"
	"pan/db"
	"pan/util"

	"github.com/gin-gonic/gin"
)

// DoSignUpHandler: 处理用户注册请求
func DoSignUpHandler(c *gin.Context) {
	username := c.Request.FormValue("username")
	passwd := c.Request.FormValue("password")
	if len(username) < 3 || len(passwd) < 5 {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "参数不合法",
			"code": -1,
		})
	}
	encryptPwd := util.Sha1([]byte(passwd + config.PasswordSalt))
	suc := db.UserSignUp(username, encryptPwd)
	if suc {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "注册成功",
			"code": 1,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "注册失败",
			"code": -2,
		})
	}
}

// DoSignInHandler: 处理用户登录请求
func DoSignInHandler(c *gin.Context) {
	username := c.Request.FormValue("username")
	passwd := c.Request.FormValue("password")
	encryptPwd := util.Sha1([]byte(passwd + config.PasswordSalt))
	// 验证密码
	pwdIsValid := db.UserSignIn(username, encryptPwd)
	if !pwdIsValid {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "密码验证失败",
			"code": -2,
		})
	}
	// 生成token
	token := util.GetToken(username)
	res := db.UpdateToken(username, token)
	if !res {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "token生成失败",
			"code": -2,
		})
	}
	resp := util.RespMsg{
		Code: 0,
		Msg:  "ok",
		Data: struct {
			Location string
			Username string
			Token    string
		}{
			Location: "/static/view/home.html",
			Username: username,
			Token:    token,
		},
	}
	c.Data(http.StatusOK, "application/json", resp.JSONBytes())
}

// DoUserInfoHandler: 处理获取用户请求
func DoUserInfoHandler(c *gin.Context) {
	username := c.Request.FormValue("username")
	user, err := db.GetUserInfo(username)
	if err != nil {
		c.Status(http.StatusInternalServerError)
		return
	}
	resp := util.RespMsg{
		Code: 1,
		Msg:  "获取用户信息成功",
		Data: user,
	}
	c.Data(http.StatusOK, "application/json", resp.JSONBytes())
}
